package com.ygxsk.carhome.ui.care;

import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.roundview.RoundTextView;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.kongzue.dialogx.dialogs.PopTip;
import com.lxj.xpopup.XPopup;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.event.EventBusQRCode;
import com.ygxsk.carhome.event.EventCardDistHistory;
import com.ygxsk.carhome.listener.AuthorityCallbackListener;
import com.ygxsk.carhome.listener.DoSomeThingListener;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.permission.PermissionSetting;
import com.ygxsk.carhome.permission.RuntimeRationale;
import com.ygxsk.carhome.response.CouponCustomer;
import com.ygxsk.carhome.response.CustomerTitle;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.sys.PermissionNameConvert;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.zxing.MyBGAQRCodeActivity;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2024/1/20  14:20
 * @Description:优惠券的选项卡  左右切换页面-废弃页2024年3月2日14:11:38
 */
public class CardMainTabActivity extends ErrorActivity implements ErrorParentExtraSingle {

    private CustomAttachPopupBg customAttachPopupBg;

    //装载的fragment
    private ArrayList<Fragment> fragmentLists = new ArrayList<>();

    //装载标题内容
    private ArrayList<CustomerTitle> titleLists = new ArrayList<>();


//    private MaterialDialog materialDialogLoadAdd;

    //该界面和标题的绑定
    private TabLayoutMediator tabLayoutMediator;

    @BindView(R.id.tab_layout_cardmain)
    TabLayout tabLayoutInCardMain;

    @BindView(R.id.viewpagerincardmain)
    ViewPager2 viewPagerInCardMain;

    //添加扫码核销的自定义弹窗；
    private MaterialDialog materialDialogCustomView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        processExtraData();

        initViews();

        //其他的类似 监听器的，提交一个客户

        //监听单个客户内容
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_card_main_tab;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.customer_carecustom));

        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                methodBack();
            }
        });

        toolbarHelper.setLayoutClose(false, "", null);

        //右侧暂时没有文字
        toolbarHelper.setLayoutRight(false, 0, "", null);

        //2024-1-10 14:00:58新增的特殊图片
        toolbarHelper.setImageViewRight(true, R.drawable.icon_rigad, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                new XPopup.Builder(mActivityInstance)
//                        .hasShadowBg(false)
//                        .isTouchThrough(true)
//                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
////                        .atView(toolbarHelper.getImageViewRight())
////                        .atView(toolbarHelper.getToolbar().findViewById(R.id.imageviewinphone))
//                        .atView(imageViewRight)
//                        .isCenterHorizontal(true)
//                        .hasShadowBg(false) // 去掉半透明背景
//                        .asCustom(new RightBubbleAttachPopup(mActivityInstance))
//                        .show();

//                showPop();
//                toggleBright();

                customAttachPopupBg = (CustomAttachPopupBg) new XPopup.Builder(mActivityInstance)
                        .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                        .isCoverSoftInput(false)//
                        .atView(v)
                        .hasShadowBg(true)//是否展示背景
                        .asCustom(new CustomAttachPopupBg(mActivityInstance, mActivityInstance, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {

                                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
                                    requestCodeQRCodePermissions();
                                } else {
                                    requestCodePermissionsXXPermissions();
                                }

                            }
                        }))
                        .show();

            }
        });

        //右侧是【编辑】
//        toolbarHelper.setLayoutRight(true, 1, getString(R.string.title_cardverifi_right), new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//
//                //携带信息跳转到【编辑-提交】页面；
//                Bundle extra_bundle = new Bundle();
//                //携带是 客户关怀 过去的 到卡券核销列表
//                extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY);
//                ActivityUtils.startActivity(extra_bundle, CardDistHistoryActivity.class);
//
//            }
//        });

    }

    @Override
    protected void onClickNodata(View v) {

        //retain

    }

    @Override
    protected void initViews() {

        //初始化fragments
        if (fragmentLists == null) {
            fragmentLists = new ArrayList<>();
        }

        if (titleLists == null) {
            titleLists = new ArrayList<>();
        }

        CustomerTitle customerTitle_card_pushed = new CustomerTitle();
        customerTitle_card_pushed.setTitleName(getResources().getString(R.string.has_card_pushed));//已发放

        CustomerTitle customerTitle_card_disted = new CustomerTitle();
        customerTitle_card_disted.setTitleName(getResources().getString(R.string.has_card_disted));//已核销

//        CustomerTitle customerTitle_fight_fail = new CustomerTitle();
//        customerTitle_fight_fail.setTitleName(ConstantSign.LEAD_FIGHT_FAIL);//战败 失败

//        CustomerTitle customerTitle_fight_success = new CustomerTitle();
//        customerTitle_fight_success.setTitleName(ConstantSign.LEAD_FIGHT_SUCCESS);//战败 成功

        titleLists.add(customerTitle_card_pushed);
        titleLists.add(customerTitle_card_disted);

//        titleLists.add(customerTitle_fight_fail);
//        titleLists.add(customerTitle_fight_success);

        fragmentLists.add(CardPushHistoryListFragment.newInstance(ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY,//
                String.valueOf(0),//
                getResources().getString(R.string.has_card_pushed)));//

        fragmentLists.add(CardDistHistoryListFragment.newInstance(ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY,//
                String.valueOf(1), //
                getResources().getString(R.string.has_card_disted)));//

//        fragmentLists.add(OrderListFragment.newInstance());
//        fragmentLists.add(OrderListFragment.newInstance());

        MyCardCustomerAdapter myCardCustomerAdapter = new MyCardCustomerAdapter(this, fragmentLists);
        viewPagerInCardMain.setAdapter(myCardCustomerAdapter);

        //设置字体颜色，第一个参数代表未点击时的字体颜色，第二个参数代表点击后的颜色
        //tabLayoutInCustomer.setTabTextColors(R.color.black,R.color.teal_700);
        //点击单个tab时背景为透明色
        //tabLayout.setTabRippleColor(ColorStateList.valueOf(Color.TRANSPARENT));

        //这种是不是将来还需要接口回来，重新绑定
        //让viewpager2与tablayout关联，实现滑动效果（滑动fragment底部tab变化，tab滑动fragment跟着滑动）
        tabLayoutMediator = new TabLayoutMediator(tabLayoutInCardMain, viewPagerInCardMain, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                //标题和数量的合并
                tab.setText(titleLists.get(position).getTitleName());
            }
        });

        tabLayoutMediator.attach();//一定要attach（）


//        //避免数据选项卡多导致数据预加载
//        tabLayoutMediator = new TabLayoutMediator(tabLayoutInFeeLive, viewPagerInFeeLive, new TabLayoutMediator.TabConfigurationStrategy() {
//            @Override
//            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
//                //标题和数量的合并
//                tab.setText(titleLists.get(position).getTitleName());
//            }
//        });
//
//        tabLayoutMediator.attach();//一定要attach（）

        tabLayoutInCardMain.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

//                LogUtils.d(ConstantSign.LOGCAT_NOMAL+"onTabSelected--onTabSelected-->"+tab.getPosition());

                viewPagerInCardMain.setCurrentItem(tab.getPosition(), false);

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    @Override
    protected void gainDatas() {

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadCardMainTab(EventBusQRCode eventBusQRCode) {

        if (eventBusQRCode != null) {

            if (eventBusQRCode.getMessage() == ExtraValue.BGAQRCODE_VALUE_FROM_CARD_DIST_HISTORY) {

                //2024年1月15日11:13:30 餐券和卡券是通用一个历史记录

                String qrCodeResult = eventBusQRCode.getContent();
                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "接收到的扫码核销值为：-->" + qrCodeResult);
                //AUTOSTEWARD_3ada8ae84d4559b666d70a8f571d27d24b3edb

                //32c48fe0534459bc63d3098c53142ed3
                //AUTOSTEWARD_3ad891e251455ab46ad60d8f571f2cd74d

                if (!TextUtils.isEmpty(qrCodeResult)) {

                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + "qrCodeResult：-->" + qrCodeResult);

                    if (qrCodeResult.startsWith(Parameterkey.QRCODE_PREFIX)) {//AUTOSTEWARD

                        //如果扫码的内容为空，那么需要提示
                        //这是跳转到-客户关怀的根据二维码获取 优惠券的详情
//                        if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY) {
//
//                            method_gainData_by_qrCode_for_rice_ticked(qrCodeResult);
//
//                        } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY) {
//
//                            method_gainData_by_qrCode_for_customer_care_card(qrCodeResult);
//
//                        } else {
//                            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "没有执行-调用核销码 获取详情接口");
//                        }

                        //放在tab里边就只有是【优惠券】的改造，而没有【餐券】的逻辑
                        method_gainData_by_qrCode_for_customer_care_card(qrCodeResult);

                    } else if (qrCodeResult.contains(Parameterkey.QRCODE_HTTP)) {
                        CommUtils.linkJumpDialog(mActivityInstance, mActivityInstance, qrCodeResult);
                    } else {
                        CommUtils.textJumpDialog(mActivityInstance, mActivityInstance, qrCodeResult);
                    }

                } else {


                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + "扫码信息是空值");

//                    if (TextUtils.isEmpty(qrCodeResult)) {//服务站运营经理的初始值-1说明没有赋值，提交不过去
                    CommUtils.checkDialog(mAlertView);
                    mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.check_qrcode_upload), true);
                    mAlertView.show();
//                    }

                }

            }
        }

    }

    //扫码完毕立即执行的操作：上传二维码的信息,根据这个二维码的信息 获取这个优惠券的信息 做展示
    //这是跳转到-客户关怀的根据二维码获取 优惠券的详情
    private void method_gainData_by_qrCode_for_customer_care_card(String _rqCode_content) {

        //如果扫码的内容为空，那么需要提示
//        if (TextUtils.isEmpty(_rqCode_content)) {//服务站运营经理的初始值-1说明没有赋值，提交不过去
//            CommUtils.checkDialog(mAlertView);
//            mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.check_qrcode_upload), true);
//            mAlertView.show();
//            return;
//        }

//        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "调用客户关怀-优惠券核销接口--method_gainData_by_qrCode_for_customer_care_card");

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
        map.put(Parameterkey.couponCode, _rqCode_content);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_ADDLATENTCUSTOMER);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.addLatentCustomer_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setAlertToUser(true);
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getCustomerCouponDetailForManager(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(CardMainTabActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CouponCustomer>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        //{"data":"","message":"无数据","code":"20002"}
                        //{"data":"","message":"无数据","code":"20002"}
                        function_response_20002(serverCode, serverMessage, addLogUpLoadInfo, true);

//                        if (!TextUtils.isEmpty(serverMessage)) {
//                            PopTip.show(serverMessage).iconWarning();
//                        } else {
//                            PopTip.show(getString(R.string.action_abnormal)).iconWarning();
//                        }

                    }
                })).subscribe(new Consumer<CouponCustomer>() {
                    @Override
                    public void accept(CouponCustomer couponCustomer) throws Throwable {

                        //获取完毕这个优惠券的信息之后，展示这个优惠券的信息；
                        if (couponCustomer != null) {
                            method_show_dist_dialog(_rqCode_content, couponCustomer);
                        } else {
                            ToastUtils.showShort(getString(R.string.action_abnormal));
                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        function_apiException(apiException);
                    }
                });

    }

    //根据扫描的二维码信息，获取餐券的信息接口
//    private void method_gainData_by_qrCode_for_rice_ticked(String _rqCode_content) {
//
////        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "调用 餐券发放-餐券核销接口--method_gainData_by_qrCode_for_rice_ticked");
//
//        HashMap<String, Object> map = new HashMap<>();
//        map.put(Parameterkey.couponCode, _rqCode_content);
//        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
//
//        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
//        addLogUpLoadInfo.setActivity(mActivityInstance);
//        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_ADDLATENTCUSTOMER);//请求数字标识
//        addLogUpLoadInfo.setUrlPath(ApiService.addLatentCustomer_url);//url地址
//        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
//        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
//        addLogUpLoadInfo.setHashMapParameter(map);
//
//        NetworkManager.getInstance().initRetrofitRxJava()
//                .create(ApiService.class)
//                .getCustomerCouponDetailForManagerRiceTick(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
//                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(CardMainTabActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
//                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CouponCustomer>() {
//                    @Override
//                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
//                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
//
//                        if (!TextUtils.isEmpty(serverMessage)) {
//                            PopTip.show(serverMessage).iconWarning();
//                        } else {
//                            PopTip.show(getString(R.string.action_abnormal)).iconWarning();
//                        }
//
//                    }
//                })).subscribe(new Consumer<CouponCustomer>() {
//                    @Override
//                    public void accept(CouponCustomer couponCustomer) throws Throwable {
//
//                        //获取完毕这个优惠券的信息之后，展示这个优惠券的信息；
//                        if (couponCustomer != null) {
//                            method_show_dist_dialog(_rqCode_content, couponCustomer);
//                        } else {
//                            ToastUtils.showShort(getString(R.string.action_abnormal));
//                        }
//
//                    }
//                }, new ErrorConsumer() {
//
//                    @Override
//                    protected void error(ApiException apiException) {
//                        //
//                    }
//                });
//
//
//    }

    //弹窗的操作：展示获取到的优惠券的信息；
    private void method_show_dist_dialog(String _rqCode_content, CouponCustomer _couponCustomer) {

        View viewCard = View.inflate(mActivityInstance, R.layout.popu_card_dist_middle_popu, null);

        if (viewCard != null) {

            //标题 卡券的
            TextView textViewCardName = (TextView) viewCard.findViewById(R.id.textviewcardname);
            //卡券的备注 使用简介
            TextView textViewCardLittleInfo = (TextView) viewCard.findViewById(R.id.textviewcardlittleinfo);
            //使用范围
            TextView textViewCardUseRangeInfo = (TextView) viewCard.findViewById(R.id.textviewcarduserangeinfo);
            //卡券的有效期
            TextView textViewCardTime = (TextView) viewCard.findViewById(R.id.textviewcardtime);
            //卡券的有效期
            RoundTextView textViewCardCancel = (RoundTextView) viewCard.findViewById(R.id.textviewcardcancel);
            //卡券的取消按钮
            RoundTextView textViewCardSure = (RoundTextView) viewCard.findViewById(R.id.textviewcardsure);

            //填充优惠券名称
            textViewCardName.setText(_couponCustomer.getCouponName());
            textViewCardLittleInfo.setText(_couponCustomer.getCouponLowAmountInfo());

            if (!TextUtils.isEmpty(_couponCustomer.getUseRangeInfo())) {
                textViewCardUseRangeInfo.setVisibility(View.VISIBLE);
                textViewCardUseRangeInfo.setText(_couponCustomer.getUseRangeInfo());
            } else {
                textViewCardUseRangeInfo.setVisibility(View.GONE);
                //textViewCardUseRangeInfo.setText(_couponCustomer.getUseRangeInfo());
            }
            textViewCardTime.setText(_couponCustomer.getEndTime());

            if (textViewCardCancel != null) {
                textViewCardCancel.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
                    @Override
                    public void onDebouncingClick(View v) {

                        //此时 弹窗是已经被弹出的
                        if (materialDialogCustomView != null) {
                            materialDialogCustomView.dismiss();
                        }

                    }
                });
            }

            if (textViewCardSure != null) {
                textViewCardSure.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
                    @Override
                    public void onDebouncingClick(View v) {

                        // : 2023-08-16 21:07 这才是真实的核销二维码卡券的接口

//                        if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY) {
//
//                            method_gainAddSubmitInfo_upLoad_for_rice_ticked(_rqCode_content);
//
//                        } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY) {
//
//                            method_gainAddSubmitInfo_upLoad_for_care_customer_card(_rqCode_content);
//
//                        }

                        method_gainAddSubmitInfo_upLoad_for_care_customer_card(_rqCode_content);

                    }
                });
            }

            //激发 弹窗弹出内容
            materialDialogCustomView = new MaterialDialog.Builder(CardMainTabActivity.this)
                    .customView(viewCard, false)
                    .contentColor(ColorUtils.getColor(R.color.buttonnomcolor))//
                    //.positiveText("确定")
                    .positiveColor(ColorUtils.getColor(R.color.dark))
                    //.negativeText("取消")
                    .canceledOnTouchOutside(false)
                    .show();

            //materialDialog.getTitleView().setTextSize(16f);

        }

    }

    @Override
    protected void methodBack() {

        methodBackFinish();

    }

    //执行上传操作:客户关怀页面，的卡券核销 这个二维码卡券；
    private void method_gainAddSubmitInfo_upLoad_for_care_customer_card(String _codeMessage) {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
        map.put(Parameterkey.couponCode, _codeMessage);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATECUSTOMERCOUPONFORVERIFY);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateCustomerCouponForVerify_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateCustomerCouponForVerify(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(CardMainTabActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        CommUtils.checkMaterialDialog(materialDialog);

                        //核销弹窗消失？
                        //核销弹窗是要有信息的
                        if (!TextUtils.isEmpty(serverMessage)) {
                            PopTip.show(serverMessage).iconWarning();
                        } else {
                            PopTip.show(getString(R.string.action_abnormal)).iconWarning();
                        }

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_SUBMIT);

                    }
                }).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        method_handler_dist_success();

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        CommUtils.checkMaterialDialog(materialDialog);
                    }
                });

    }

    //餐券发放-的核销餐券接口
//    private void method_gainAddSubmitInfo_upLoad_for_rice_ticked(String _codeMessage) {
//
//        HashMap<String, Object> map = new HashMap<>();
//        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
//        map.put(Parameterkey.couponCode, _codeMessage);
//
//        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
//        addLogUpLoadInfo.setActivity(mActivityInstance);
//        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATECUSTOMERCOUPONFORVERIFY_RICKET);//请求数字标识
//        addLogUpLoadInfo.setUrlPath(ApiService.updateCustomerCouponForVerify_ricket_url);//url地址
//        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
//        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
//        addLogUpLoadInfo.setHashMapParameter(map);
//
//        NetworkManager.getInstance().initRetrofitRxJava()
//                .create(ApiService.class)
//                .updateCustomerCouponForVerify_Ricket(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
//                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(CardMainTabActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
//                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
//                    @Override
//                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
//                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
//
//                        CommUtils.checkMaterialDialog(materialDialog);
//
//                        //核销弹窗是要有信息的
//                        if (!TextUtils.isEmpty(serverMessage)) {
//                            PopTip.show(serverMessage).iconWarning();
//                        } else {
//                            PopTip.show(getString(R.string.action_abnormal)).iconWarning();
//                        }
//
//                    }
//                })).doOnSubscribe(new Consumer<Disposable>() {
//                    @Override
//                    public void accept(Disposable disposable) throws Throwable {
//
//                        method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_SUBMIT);
//
//                    }
//                }).subscribe(new Consumer<String>() {
//                    @Override
//                    public void accept(String stringValue) throws Throwable {
//
//                        CommUtils.checkMaterialDialog(materialDialog);
//
//                        method_handler_dist_success();
//
//                    }
//                }, new ErrorConsumer() {
//
//                    @Override
//                    protected void error(ApiException apiException) {
//                        CommUtils.checkMaterialDialog(materialDialog);
//                    }
//                });
//
//    }

    //卡券核销成功之后的处理值,通用；
    private void method_handler_dist_success() {

        //只有提交成功 关闭这个核销弹窗
        CommUtils.checkMaterialDialog(materialDialog);
        CommUtils.checkMaterialDialog(materialDialogCustomView);

        //通知主页列表刷新
        EventCardDistHistory eventCardDistHistory = new EventCardDistHistory();
        eventCardDistHistory.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CARD_DIST_HISTORY_MAIN_LIST);
        EventBus.getDefault().post(eventCardDistHistory);

        String distSuccess = getResources().getString(R.string.card_dist_success);
        PopTip.show(distSuccess).iconSuccess();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        CommUtils.checkMaterialDialog(materialDialog);
        CommUtils.checkMaterialDialog(materialDialogCustomView);

        if (customAttachPopupBg != null) {
            customAttachPopupBg.onDestroy();
            customAttachPopupBg = null;
        }

        EventBus.getDefault().unregister(this);

    }

    @Override
    public void processExtraData() {

        //use the data received here
        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {

            flag_jumpfrom_where = bundle.getInt(ExtraKey.EXTRA_JUMPFROM_WHERE);

            //LogUtils.d(ConstantSign.LOGCAT_NOMAL + extra_jumpfrom_where);

//            station_shopId_upLoad = bundle.getString(ExtraKey.EXTRA_ASSETINSIDEBEAN_SHOPID);

            //这个特殊，采用同一个对象；
            //服务站的顶部选择列表---这里取到的肯定是空值，因为上一个页面没有携带
//            extra_assetStationInfoListForAddAsset_loacalDB = bundle.getParcelableArrayList(ExtraKey.EXTRA_ASSETSTATIONINFOLISTFORADDASSET);

            //资产的归属方 列表，
//            extra_assetUnderBusinessInfoListOutSide = bundle.getParcelableArrayList(ExtraKey.EXTRA_ASSETUNDERBUSINESSINFOLISTOUTSIDE);

        }

    }

    /*
     * @Author:itchenqi175@163.com
     * @Time:2024/1/20  14:33
     * @Description:卡券发放的主页列表的适配器选项卡的
     */
    private class MyCardCustomerAdapter extends FragmentStateAdapter {
        private ArrayList<Fragment> fragmentList;

        public MyCardCustomerAdapter(@NonNull FragmentActivity fragmentActivity, ArrayList<Fragment> fragments) {
            super(fragmentActivity);
            this.fragmentList = fragments;
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getItemCount() {
            return fragmentList.size();
        }

    }


    //android13的权限判断内容
    private void requestCodePermissionsXXPermissions() {

        try {

            //do

            if (!XXPermissions.isGranted(mActivityInstance, com.hjq.permissions.Permission.CAMERA)//
                    || !XXPermissions.isGranted(mActivityInstance, com.hjq.permissions.Permission.READ_MEDIA_IMAGES)) {

                CommUtils.checkMaterialDialog(materialDialog);

                materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_ALBUM, new AuthorityCallbackListener() {
                    @Override
                    public void doSomeThing() {

                        CommUtils.checkMaterialDialog(materialDialog);

                        XXPermissions.with(mActivityInstance)
                                // 适配分区存储应该这样写
                                //.permission(Permission.Group.STORAGE)
                                // 不适配分区存储应该这样写
                                .permission(com.hjq.permissions.Permission.CAMERA)//
                                .permission(com.hjq.permissions.Permission.READ_MEDIA_IMAGES)//
//                                    .permission(com.hjq.permissions.Permission.READ_MEDIA_VIDEO)//
//                                    .permission(com.hjq.permissions.Permission.READ_MEDIA_AUDIO)//
                                //).permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE
//                                                        .interceptor(new PermissionInterceptor())
                                .request(new OnPermissionCallback() {

                                    @Override
                                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                        if (!allGranted) {
                                            // TODO: 2024/1/23 18:50 权限这里要不要给提示？权限没通过
                                            return;
                                        }

                                        Toaster.show(String.format(mActivityInstance.getResources().getString(R.string.demo_obtain_permission_success_hint), PermissionNameConvert.getPermissionString(mActivityInstance, permissions)));

                                        openMain();

                                    }
                                });
                    }
                });

            } else {

                openMain();

            }


        } catch (Exception e) {
            //catch
            e.printStackTrace();
        }


    }

    private void requestCodeQRCodePermissions() {

        if (!AndPermission.hasPermissions(mActivityInstance, Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)) {

            CommUtils.checkMaterialDialog(materialDialog);

            materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_STORAGE, new AuthorityCallbackListener() {
                @Override
                public void doSomeThing() {

                    CommUtils.checkMaterialDialog(materialDialog);

                    //2018年06月05日发现这里添加SD卡的存储权限内容
                    AndPermission.with(mActivityInstance)//
                            .runtime()//
                            .permission(
                                    Permission.CAMERA,//
                                    Permission.READ_EXTERNAL_STORAGE,//
                                    Permission.WRITE_EXTERNAL_STORAGE)//
                            .rationale(new RuntimeRationale())//
                            .onGranted(new Action<List<String>>() {//
                                @Override
                                public void onAction(List<String> permissions) {

                                    openMain();

                                }
                            }).onDenied(new Action<List<String>>() {
                                @Override
                                public void onAction(List<String> permissions) {
                                    //弹出失败弹窗
                                    if (AndPermission.hasAlwaysDeniedPermission(mActivityInstance, permissions)) {//
                                        (new PermissionSetting(mActivityInstance)).showSetting(ConstantApi.PERMISSION_NORMAL, mActivityInstance, permissions);//
                                    }
                                }
                            }).start();

                }
            });

        } else {

            openMain();

        }

    }

    //打开扫描二维码的能力
    private void openMain() {

        Bundle bundle = new Bundle();
        bundle.putInt(ExtraKey.EXTRA_QRCODE_INFO, 0);
        bundle.putInt(ExtraKey.BGAQRCODE_KEY, ExtraValue.BGAQRCODE_VALUE_FROM_CARD_DIST_HISTORY);
        ActivityUtils.startActivity(bundle, MyBGAQRCodeActivity.class);

//        dismiss();

    }

}